<template>
  <div class="publish-container">
    <!-- 发布类型选择 -->
    <div class="type-selector" :class="{ 'lost': isLostType, 'found': !isLostType }">
      <div class="type-option lost" 
        :class="{ active: isLostType }"
        @click="handleTypeChange('lost')">
        <div class="icon-wrapper">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="text">
          <h3>发布失物信息</h3>
          <p>丢失物品？在这里发布寻物启事</p>
        </div>
        <div class="hover-effect"></div>
      </div>
      <div class="type-option found" 
        :class="{ active: !isLostType }"
        @click="handleTypeChange('found')">
        <div class="icon-wrapper">
          <el-icon><Present /></el-icon>
        </div>
        <div class="text">
          <h3>发布招领信息</h3>
          <p>捡到物品？在这里发布招领启事</p>
        </div>
        <div class="hover-effect"></div>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container" :class="{ 'lost': isLostType, 'found': !isLostType }">
      <div class="form-header">
        <div class="step-indicator">
          <div class="step" :class="{ active: currentStep >= 1 }">
            <span class="step-number">1</span>
            <span class="step-text">基本信息</span>
          </div>
          <div class="step-line"></div>
          <div class="step" :class="{ active: currentStep >= 2 }">
            <span class="step-number">2</span>
            <span class="step-text">图片上传</span>
          </div>
          <div class="step-line"></div>
          <div class="step" :class="{ active: currentStep >= 3 }">
            <span class="step-number">3</span>
            <span class="step-text">联系方式</span>
          </div>
        </div>
      </div>

      <div class="form-content">
        <!-- 步骤1：基本信息 -->
        <div class="form-step" v-show="currentStep === 1">
          <div class="input-group">
            <label>物品名称</label>
            <input 
              v-model="formData.title"
              type="text"
              :placeholder="isLostType ? '输入丢失的物品名称' : '输入拾获的物品名称'"
              class="custom-input"
            >
          </div>

          <div class="input-group">
            <label>物品类别</label>
            <div class="category-options">
              <div 
                v-for="item in categories"
                :key="item.value"
                class="category-item"
                :class="{ active: formData.category === item.value }"
                @click="formData.category = item.value"
              >
                <span class="category-icon">{{ item.icon }}</span>
                <span class="category-label">{{ item.label }}</span>
              </div>
            </div>
          </div>

          <div class="input-group">
            <label>{{ timeLabel }}</label>
            <el-date-picker
              v-model="formData.time"
              type="datetime"
              :placeholder="timePlaceholder"
              class="custom-date-picker"
            />
          </div>

          <div class="input-group">
            <label>{{ locationLabel }}</label>
            <div class="location-selector">
              <div class="location-groups">
                <div 
                  v-for="area in locations"
                  :key="area.value"
                  class="location-group"
                >
                  <div class="group-title">{{ area.label }}</div>
                  <div class="group-options">
                    <div 
                      v-for="place in area.children"
                      :key="place.value"
                      class="location-option"
                      :class="{ active: isLocationSelected(area.value, place.value) }"
                      @click="selectLocation(area.value, place.value)"
                    >
                      {{ place.label }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="input-group">
            <label>物品描述</label>
            <textarea
              v-model="formData.description"
              :placeholder="isLostType ? '详细描述丢失物品的特征、丢失时的具体情况等' : '详细描述拾获物品的特征、拾获时的具体情况等'"
              class="custom-textarea"
              rows="4"
            ></textarea>
          </div>
        </div>

        <!-- 步骤2：图片上传 -->
        <div class="form-step" v-show="currentStep === 2">
          <div class="upload-section">
            <div class="upload-area" @click="triggerUpload">
              <input
                type="file"
                ref="fileInput"
                multiple
                accept="image/*"
                class="file-input"
                @change="handleFileChange"
              >
              <div class="upload-placeholder">
                <i class="upload-icon">📸</i>
                <h3>点击上传图片</h3>
                <p>支持jpg、png格式，最多5张</p>
              </div>
            </div>
            <div class="image-preview" v-if="formData.images.length">
              <div 
                v-for="(image, index) in formData.images"
                :key="index"
                class="preview-item"
              >
                <img :src="getImageUrl(image)" alt="预览图">
                <div class="preview-actions">
                  <button class="delete-btn" @click="removeImage(index)">
                    <el-icon><Delete /></el-icon>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤3：联系方式 -->
        <div class="form-step" v-show="currentStep === 3">
          <div class="contact-form">
            <div class="input-group">
              <label>联系人</label>
              <input
                v-model="formData.contact.name"
                type="text"
                placeholder="请输入联系人姓名"
                class="custom-input"
              >
            </div>
            <div class="input-group">
              <label>手机号码</label>
              <input
                v-model="formData.contact.phone"
                type="tel"
                placeholder="请输入联系电话"
                class="custom-input"
              >
            </div>
            <div class="input-group">
              <label>微信号（选填）</label>
              <input
                v-model="formData.contact.wechat"
                type="text"
                placeholder="请输入微信号"
                class="custom-input"
              >
            </div>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <button 
          v-if="currentStep > 1"
          class="action-btn prev"
          @click="prevStep"
        >
          上一步
        </button>
        <button 
          v-if="currentStep < 3"
          class="action-btn next"
          @click="nextStep"
        >
          下一步
        </button>
        <button 
          v-else
          class="action-btn submit"
          @click="handleSubmit"
        >
          发布信息
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Warning, Present, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const fileInput = ref<HTMLInputElement | null>(null)
const currentStep = ref(1)

// 判断是否为失物发布
const isLostType = computed(() => route.query.type === 'lost')

// 表单数据
const formData = ref({
  title: '',
  category: '',
  time: '',
  location: [] as string[],
  description: '',
  images: [] as File[],
  contact: {
    name: '',
    phone: '',
    wechat: ''
  }
})

// 分类选项
const categories = [
  { value: 'electronics', label: '电子设备', icon: '📱' },
  { value: 'cards', label: '证件卡片', icon: '💳' },
  { value: 'books', label: '书籍资料', icon: '📚' },
  { value: 'clothing', label: '衣物饰品', icon: '👔' },
  { value: 'others', label: '其他', icon: '📦' }
]

// 地点选项
const locations = [
  {
    value: 'teaching',
    label: '教学区',
    children: [
      { value: 'building-a', label: 'A教学楼' },
      { value: 'building-b', label: 'B教学楼' }
    ]
  },
  {
    value: 'living',
    label: '生活区',
    children: [
      { value: 'canteen', label: '食堂' },
      { value: 'dormitory', label: '宿舍区' }
    ]
  }
]

// 动态标签文本
const timeLabel = computed(() => isLostType.value ? '丢失时间' : '拾获时间')
const timePlaceholder = computed(() => isLostType.value ? '请选择丢失时间' : '请选择拾获时间')
const locationLabel = computed(() => isLostType.value ? '丢失地点' : '拾获地点')

// 处理类型切换
const handleTypeChange = (type: string) => {
  router.replace({ query: { ...route.query, type } })
}

// 处理地点选择
const isLocationSelected = (area: string, place: string) => {
  return formData.value.location.includes(`${area}-${place}`)
}

const selectLocation = (area: string, place: string) => {
  const location = `${area}-${place}`
  const index = formData.value.location.indexOf(location)
  if (index === -1) {
    formData.value.location.push(location)
  } else {
    formData.value.location.splice(index, 1)
  }
}

// 处理图片上传
const triggerUpload = () => {
  fileInput.value?.click()
}

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files) {
    const newFiles = Array.from(input.files)
    if (formData.value.images.length + newFiles.length > 5) {
      ElMessage.warning('最多只能上传5张图片')
      return
    }
    formData.value.images.push(...newFiles)
  }
}

const getImageUrl = (file: File) => {
  return URL.createObjectURL(file)
}

const removeImage = (index: number) => {
  formData.value.images.splice(index, 1)
}

// 步骤控制
const nextStep = () => {
  if (validateCurrentStep()) {
    currentStep.value++
  }
}

const prevStep = () => {
  currentStep.value--
}

// 表单验证
const validateCurrentStep = () => {
  switch (currentStep.value) {
    case 1:
      if (!formData.value.title) {
        ElMessage.warning('请输入物品名称')
        return false
      }
      if (!formData.value.category) {
        ElMessage.warning('请选择物品类别')
        return false
      }
      if (!formData.value.time) {
        ElMessage.warning('请选择时间')
        return false
      }
      if (!formData.value.location.length) {
        ElMessage.warning('请选择地点')
        return false
      }
      if (!formData.value.description) {
        ElMessage.warning('请输入物品描述')
        return false
      }
      break
    case 2:
      // 图片上传是可选的
      break
    case 3:
      if (!formData.value.contact.name) {
        ElMessage.warning('请输入联系人姓名')
        return false
      }
      if (!formData.value.contact.phone) {
        ElMessage.warning('请输入联系电话')
        return false
      }
      if (!/^1[3-9]\d{9}$/.test(formData.value.contact.phone)) {
        ElMessage.warning('请输入正确的手机号码')
        return false
      }
      break
  }
  return true
}

// 处理提交
const handleSubmit = async () => {
  if (!validateCurrentStep()) return
  
  try {
    // TODO: 调用接口提交数据
    console.log('提交的表单数据：', formData.value)
    ElMessage.success('发布成功')
    router.push('/')
  } catch (error) {
    console.error('提交失败：', error)
    ElMessage.error('发布失败，请重试')
  }
}
</script>

<style scoped lang="scss">
.publish-container {
  max-width: 1200px;
  min-width: $min-width;
  margin: 0 auto;
  padding: $spacing-huge;
  
  @media (max-width: 768px) {
    padding: $spacing-base;
  }
}

.type-selector {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: $spacing-large;
  margin-bottom: $spacing-huge;

  .type-option {
    position: relative;
    height: 180px;
    border-radius: $border-radius-large;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    padding: $spacing-large;
    
    &.lost {
      background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
      
      &:not(.active) {
        opacity: 0.6;
      }
    }
    
    &.found {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      
      &:not(.active) {
        opacity: 0.6;
      }
    }

    .icon-wrapper {
      width: 64px;
      height: 64px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: $spacing-large;

      .el-icon {
        font-size: 32px;
        color: white;
      }
    }

    .text {
      color: white;

      h3 {
        font-size: 24px;
        margin: 0 0 $spacing-mini;
      }

      p {
        font-size: 16px;
        margin: 0;
        opacity: 0.9;
      }
    }

    .hover-effect {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: radial-gradient(circle at center, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    &:hover {
      transform: translateY(-5px);

      .hover-effect {
        opacity: 1;
      }
    }

    &.active {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0,0,0,0.15);
    }
  }
}

.form-container {
  background: white;
  border-radius: $border-radius-large;
  box-shadow: $card-shadow;
  overflow: hidden;

  &.lost {
    --theme-color: #ff6b6b;
    --theme-gradient: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  }

  &.found {
    --theme-color: #4facfe;
    --theme-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  .form-header {
    padding: $spacing-large;
    background: var(--theme-gradient);
    
    .step-indicator {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: $spacing-large;

      .step {
        display: flex;
        align-items: center;
        gap: $spacing-base;
        color: rgba(255, 255, 255, 0.6);
        transition: all 0.3s ease;

        .step-number {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.2);
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
        }

        &.active {
          color: white;

          .step-number {
            background: white;
            color: var(--theme-color);
          }
        }
      }

      .step-line {
        flex: 1;
        height: 2px;
        background: rgba(255, 255, 255, 0.2);
        max-width: 100px;
      }
    }
  }

  .form-content {
    padding: $spacing-huge;

    .form-step {
      animation: fadeIn 0.3s ease;
    }

    .input-group {
      margin-bottom: $spacing-large;

      label {
        display: block;
        font-size: 16px;
        color: $text-primary;
        margin-bottom: $spacing-base;
      }

      .custom-input {
        width: 100%;
        height: 48px;
        padding: 0 $spacing-base;
        border: 2px solid $border-color;
        border-radius: $border-radius-base;
        font-size: 16px;
        transition: all 0.3s ease;

        &:focus {
          border-color: var(--theme-color);
          outline: none;
          box-shadow: 0 0 0 3px rgba(var(--theme-color), 0.1);
        }
      }

      .custom-textarea {
        width: 100%;
        padding: $spacing-base;
        border: 2px solid $border-color;
        border-radius: $border-radius-base;
        font-size: 16px;
        resize: vertical;
        min-height: 120px;
        transition: all 0.3s ease;

        &:focus {
          border-color: var(--theme-color);
          outline: none;
          box-shadow: 0 0 0 3px rgba(var(--theme-color), 0.1);
        }
      }
    }

    .category-options {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: $spacing-base;

      .category-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: $spacing-base;
        border: 2px solid $border-color;
        border-radius: $border-radius-base;
        cursor: pointer;
        transition: all 0.3s ease;

        .category-icon {
          font-size: 24px;
          margin-bottom: $spacing-mini;
        }

        &:hover {
          border-color: var(--theme-color);
          background: rgba(var(--theme-color), 0.05);
        }

        &.active {
          border-color: var(--theme-color);
          background: var(--theme-gradient);
          color: white;
        }
      }
    }

    .location-selector {
      .location-groups {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: $spacing-large;

        .location-group {
          .group-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: $spacing-base;
            color: $text-primary;
          }

          .group-options {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: $spacing-base;

            .location-option {
              padding: $spacing-base;
              border: 2px solid $border-color;
              border-radius: $border-radius-base;
              text-align: center;
              cursor: pointer;
              transition: all 0.3s ease;

              &:hover {
                border-color: var(--theme-color);
                background: rgba(var(--theme-color), 0.05);
              }

              &.active {
                border-color: var(--theme-color);
                background: var(--theme-gradient);
                color: white;
              }
            }
          }
        }
      }
    }

    .upload-section {
      .upload-area {
        position: relative;
        height: 200px;
        border: 2px dashed $border-color;
        border-radius: $border-radius-base;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--theme-color);
          background: rgba(var(--theme-color), 0.05);
        }

        .file-input {
          display: none;
        }

        .upload-placeholder {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          text-align: center;

          .upload-icon {
            font-size: 48px;
            margin-bottom: $spacing-base;
          }

          h3 {
            font-size: 20px;
            margin: 0 0 $spacing-mini;
            color: $text-primary;
          }

          p {
            color: $text-secondary;
            margin: 0;
          }
        }
      }

      .image-preview {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: $spacing-base;
        margin-top: $spacing-large;

        .preview-item {
          position: relative;
          border-radius: $border-radius-base;
          overflow: hidden;

          img {
            width: 100%;
            height: 150px;
            object-fit: cover;
          }

          .preview-actions {
            position: absolute;
            top: $spacing-mini;
            right: $spacing-mini;

            .delete-btn {
              width: 32px;
              height: 32px;
              border-radius: 50%;
              background: rgba(255, 255, 255, 0.9);
              border: none;
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: center;
              color: #ff4757;
              transition: all 0.3s ease;

              &:hover {
                background: #ff4757;
                color: white;
              }
            }
          }
        }
      }
    }
  }

  .form-actions {
    padding: $spacing-large;
    border-top: 1px solid $border-lighter;
    display: flex;
    justify-content: center;
    gap: $spacing-large;

    .action-btn {
      min-width: 160px;
      height: 48px;
      border-radius: $border-radius-base;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s ease;

      &.prev {
        background: white;
        border: 2px solid $border-color;
        color: $text-regular;

        &:hover {
          border-color: var(--theme-color);
          color: var(--theme-color);
        }
      }

      &.next,
      &.submit {
        background: var(--theme-gradient);
        border: none;
        color: white;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(var(--theme-color), 0.3);
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 